const fs = require('fs');

// 读取 CSS 文件内容
const cssFiles = ['zl.css', 'zl2.css'];
let cssContent = '';

// 读取所有 CSS 文件
cssFiles.forEach(file => {
  cssContent += fs.readFileSync(file, 'utf8') + '\n';
});

// 解析 CSS 内容
const parseCSS = (css) => {
  const rules = {};
  const regex = /([^{]+){([^}]*)}/g;
  let match;

  while ((match = regex.exec(css)) !== null) {
    const selectors = match[1].trim().split(',').map(s => s.trim());
    const properties = match[2].trim().split(';').filter(prop => prop.trim() !== '');

    selectors.forEach(selector => {
      if (!rules[selector]) {
        rules[selector] = {};
      }

      properties.forEach(prop => {
        const [key, value] = prop.split(':').map(str => str.trim());
        if (key && value) {
          rules[selector][key] = value;
        }
      });
    });
  }

  return rules;
};

// 合并规则
const mergeRules = (rules) => {
  const merged = {};

  Object.keys(rules).forEach(selector => {
    if (!merged[selector]) {
      merged[selector] = {};
    }

    Object.assign(merged[selector], rules[selector]);
  });

  return merged;
};

// 生成 CSS 内容
const generateCSS = (rules) => {
  let css = '';

  Object.keys(rules).forEach(selector => {
    css += `${selector} {\n`;
    Object.keys(rules[selector]).forEach(key => {
      css += `  ${key}: ${rules[selector][key]};\n`;
    });
    css += `}\n`;
  });

  return css;
};

// 解析、合并和生成 CSS
const parsedRules = parseCSS(cssContent);
const mergedRules = mergeRules(parsedRules);
const mergedCSS = generateCSS(mergedRules);

// 写入合并后的 CSS 文件
fs.writeFileSync('merged.css', mergedCSS);
console.log('CSS files have been merged into merged.css');
